package thread;

import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPoolExecutor{//自定义线程池
    private ArrayList<Thread>threadArrayList=new ArrayList<>();
    //用来存储后续设定的线程,方便后续处理
    private BlockingQueue<Runnable> queue=new ArrayBlockingQueue<>(4);
    //用来存储执行任务的队列
    public MyThreadPoolExecutor(int n){//n为线程池创建出来的线程数目
        for(int i=0;i<n;i++){
            Thread t=new Thread(()->{
                while(true){

                    try {
                        Runnable runnable=queue.take();//取出需要执行的任务,这里的队列使用take,是带有阻塞功能的
                        runnable.run();//取出来之后进行使用
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }
            });
            threadArrayList.add(t);
            t.start();
        }

    }
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);//这里进行放入任务
    }


}

public class ThreadDemo30 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPoolExecutor executor=new MyThreadPoolExecutor(4);
        for(int i=0;i<1000;i++){
            int n=i;//因为变量捕获
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行任务"+n+"线程为"+Thread.currentThread().getName());
                }
            });
        }
    }
}
